package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.chat.entry.dto.group.CreateGroupChatDTO;
import com.chat.entry.enums.GroupMemberIsDisturb;
import com.chat.entry.enums.GroupMemberRole;
import com.chat.entry.po.GroupChatInformation;
import com.chat.entry.po.GroupMember;
import com.chat.mapper.GroupChatInformationMapper;
import com.chat.mapper.GroupMemberMapper;
import com.chat.result.Result;
import com.chat.service.IGroupChatInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.utils.UidUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 群聊信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-21
 */
@Service
@RequiredArgsConstructor
public class GroupChatInformationServiceImpl extends ServiceImpl<GroupChatInformationMapper, GroupChatInformation> implements IGroupChatInformationService {
    private final GroupMemberServiceImpl groupMemberService;

    @Transactional
    @Override
    public Result createGroupChat(CreateGroupChatDTO createGroupChatDTO) {
        // 生成随机的11位群号 (唯一)
        String groupUid = generateUniqueGroupUid();

        GroupChatInformation groupChatInformation = new GroupChatInformation();
        groupChatInformation.setGroupUid(groupUid);
        groupChatInformation.setName(createGroupChatDTO.getGroupName());
        groupChatInformation.setOwnerId(createGroupChatDTO.getCreateUserId());
        groupChatInformation.setCreateTime(LocalDateTime.now());
        groupChatInformation.setUpdateTime(LocalDateTime.now());
        groupChatInformation.setUpdateUserId(createGroupChatDTO.getCreateUserId());

        boolean save = save(groupChatInformation);

        if (!save) {
            return Result.error("创建群聊失败");
        }

        Integer groupId = groupChatInformation.getId();

        List<GroupMember> members = new ArrayList<>();

        // 群主
        GroupMember owner = new GroupMember();
        owner.setGroupId(groupId);
        owner.setUserId(createGroupChatDTO.getCreateUserId());
        owner.setRole(GroupMemberRole.OWNER);
        owner.setIsDisturb(GroupMemberIsDisturb.DISTURB);
        owner.setJoinTime(LocalDateTime.now());
        owner.setUpdateTime(LocalDateTime.now());
        members.add(owner);

        // 普通成员
        createGroupChatDTO.getMemberIds().forEach(memberId -> {
            GroupMember member = new GroupMember();
            member.setGroupId(groupId);
            member.setUserId(memberId);
            member.setRole(GroupMemberRole.MEMBER);
            member.setIsDisturb(GroupMemberIsDisturb.DISTURB);
            member.setJoinTime(LocalDateTime.now());
            member.setUpdateTime(LocalDateTime.now());
            members.add(member);
        });

        // 批量保存
        groupMemberService.saveBatch(members);

        return Result.success("创建成功", groupChatInformation);
    }

    /**
     * 生成唯一群号
     */
    private String generateUniqueGroupUid() {
        String groupUid;
        do {
            groupUid = UidUtil.generateGroupUid();
        } while (getOne(new LambdaQueryWrapper<GroupChatInformation>()
                .eq(GroupChatInformation::getGroupUid, groupUid)) != null);

        return groupUid;
    }

    @Override
    public Result inviteFriendToGroupChat(Integer groupchatId, List<Integer> userIds) {
        // 判断群聊是否存在
        GroupChatInformation groupChatInformation = getOne(new LambdaQueryWrapper<GroupChatInformation>()
                .eq(GroupChatInformation::getId, groupchatId));
        if (groupChatInformation == null) {
            return Result.error("群聊不存在");
        }

        List<GroupMember> members = new ArrayList<>();
        userIds.forEach(userId -> {
            GroupMember groupMember = new GroupMember();
            groupMember.setGroupId(groupchatId);
            groupMember.setUserId(userId);
            groupMember.setRole(GroupMemberRole.MEMBER);
            groupMember.setIsDisturb(GroupMemberIsDisturb.DISTURB);
            groupMember.setJoinTime(LocalDateTime.now());
            groupMember.setUpdateTime(LocalDateTime.now());
            members.add(groupMember);
        });

        // 批量保存
        boolean invite = groupMemberService.saveBatch(members);
        if (!invite) {
            return Result.error("邀请失败");
        }

        return Result.success("邀请成功", groupChatInformation);
    }

    @Override
    public Result removeGroupChat(Integer groupChatId, Integer userId) {
        GroupMember groupMember = groupMemberService.getOne(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getGroupId, groupChatId)
                        .eq(GroupMember::getUserId, userId)
        );

        if (groupMember == null) {
            return Result.error("他(她)不存在群聊当中");
        }

        boolean remove = groupMemberService.removeById(groupMember);
        if (!remove) {
            return Result.error("踢出群聊失败");
        }

        return Result.success("踢出群聊成功", null);
    }

    @Override
    public Result leaveGroupChat(Integer groupChatId, Integer userId) {
        GroupMember groupMember = groupMemberService.getOne(
                new LambdaQueryWrapper<GroupMember>()
                        .eq(GroupMember::getGroupId, groupChatId)
                        .eq(GroupMember::getUserId, userId)
        );

        if (groupMember == null) {
            return Result.error("他(她)不存在群聊当中");
        }

        boolean remove = groupMemberService.removeById(groupMember);
        if (!remove) {
            return Result.error("踢出群聊失败");
        }

        return Result.success("退出群聊成功", null);
    }
}
